<?php

class HomeController extends BaseController {

	public function index()
	{
	    $indexlist = Post::orderBy('created_at', 'desc')->paginate(10) ;
	    $nav = $this->getNav() ;
	    $newPosts = $this->getNewPosts(5) ;
	    $commentPosts = $this->getCommentPosts(5) ;
	    
		return View::make('Home.index')
    		->with('indexlist', $indexlist)
    		->with('nav', $nav)
    		->with('newPosts', $newPosts)
		      ->with('commentPosts', $commentPosts);
		
	}
	
	public function lists($id){
	    
	   // $posts = Post::where('ptid', '=', $id)->paginate(10)->get();
	    $posts = Post::where('ptid', '=', $id)->paginate(5);
	    
	    $nav = $this->getNav() ;
	    $newPosts = $this->getNewPosts(5) ;
	    $commentPosts = $this->getCommentPosts(5) ;
		return View::make('Home.lists')->with('nav', $nav)->with('posts', $posts)->with('newPosts', $newPosts)->with('commentPosts', $commentPosts) ;
	}
	
	public function show($id){
	    $post = Post::find($id) ;
	    $comments = Comment::where('post_id', '=', $id)->where('status', '=', '1')->paginate(5) ;
	    $nav = $this->getNav() ;
	    $newPosts = $this->getNewPosts(5) ;
	    $commentPosts = $this->getCommentPosts(5) ;
		return View::make('Home.show')->with('nav', $nav)->with('post', $post)->with('newPosts', $newPosts)->with('comments', $comments)->with('commentPosts', $commentPosts) ;
	}

	
	public function search(){
		$keyword = Input::get('keyword');
		$posts = Post::where(DB::raw('CONCAT(title,body)'), 'like', '%'.$keyword.'%')->paginate(5) ;
		
		$nav = $this->getNav() ;
		$newPosts = $this->getNewPosts(5) ;
		$commentPosts = $this->getCommentPosts(5) ;
	    return View::make('Home.search')->with('nav', $nav)->with('posts', $posts)->with('newPosts', $newPosts)->with('commentPosts', $commentPosts) ;
	}
	
	public function comment(){

        //rules
        $rules = array(
            'email'       => 'required',
            'comment'      => 'required', 
            'status'    =>  'required', 
            'post_id'   =>  'required'
        );
        $validator = Validator::make(Input::all(), $rules);
        $postid = Input::get('post_id') ;
        
        //validator 
        if ($validator->fails()) {
            return Redirect::to('post/' . $postid)->withErrors($validator);
        } else {
            
            $comment = new \Comment();
            $comment->email        =   Input::get('email');
            $comment->comment     =   Input::get('comment');
            $comment->status     =   Input::get('status');
            $comment->post_id  =   $postid;
            $comment->pid         =   Input::get('pid');
            
            if ( $comment->save() ) {
                // redirect
                Session::flash('message', '评论成功，等待审核中....');
                return Redirect::to('show/' . $postid);
            }else{
                Session::flash('message', '评论失败，信息不完整，请重新填写！');
                return Redirect::to('show/' . $postid);
            }
		
	   }
	}
	
}